package com.hualian.ticket.controller;


import com.hualian.ticket.exception.BusinessException;
import com.hualian.ticket.pojo.User;
import com.hualian.ticket.service.UserService;
import com.hualian.ticket.util.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @author 陈静
 * @date 2020/10/21 11:18
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;
    //java操作redis，是借助于RedisTemplate
    @Resource
    RedisTemplate<String, String> redisTemplate;

    @PostMapping("/reg")
    public Map reg(@RequestParam("name") String name, @RequestParam("phone") String phone, @RequestParam("captcha") String captcha) throws BusinessException {
        //判断验证码是否合法
        //1.利用RedisTemplate绑定要操作的数据类型，生成对应的操作符对象
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //访问key - value
        String s = operations.get("sms:" + phone);
        if(s==null){
            throw new BusinessException("验证码失效，请重新获得");
        }
        //判断该手机号是否已注册
        User byPhone = userService.findByPhone(phone);
        if(byPhone!=null){
            throw new BusinessException("用户已经注册，请更换手机号，或者登录");
        }
        JsonResult jsonResult = new JsonResult();
        if (s.equals(captcha)) {
            userService.insertUser(name, phone, new Date());
            jsonResult.setCode("1");
            jsonResult.setMsg("success");
        } else {
            throw new BusinessException("验证码不正确,请重新输入");
        }
        //合法，将个人信息+注册时间 添加到数据库
        //不合法，返回注册失败，验证码不正确
        return jsonResult.getValues();
    }

    @PostMapping("/login")
    public Map login(@RequestParam("phone") String phone) throws BusinessException {
        User byPhone = userService.findByPhone(phone);
        JsonResult jsonResult = new JsonResult();
        if (byPhone != null) {
            jsonResult.setCode("1");
            jsonResult.setMsg("登录成功！");
            jsonResult.setData(byPhone);
        } else {
            throw new BusinessException("您还没有注册账号，请先注册账号！");
        }
        return jsonResult.getValues();
    }

}
